import { t } from 'i18next'
import React, { useEffect, useRef } from 'react'
import { InnerInputRef, Input, Modal } from '@kedacom/react-next'
import shallow from 'zustand/shallow'
import { useKdPreSettingDialogStore } from './store'
import { IconTips, Wrap } from './style'
import { getCheckPreNameRule } from '@/utils'
import { useGlobalStore } from '@/store/global'

function Main() {
	const { dialogTitle, update, isOpen, init, planOptions, handlePlanClick, name, emptyMsg, handleConfirm } =
		useKdPreSettingDialogStore(
			(state) => ({
				name: state.name,
				init: state.init,
				update: state.update,
				isOpen: state.isOpen,
				dialogTitle: state.dialogTitle,
				planOptions: state.planOptions,
				handlePlanClick: state.handlePlanClick,
				emptyMsg: state.emptyMsg,
				handleConfirm: state.handleConfirm,
			}),
			shallow
		)

	useEffect(() => {
		isOpen && init()
	}, [isOpen])

	const inputRef = useRef<InnerInputRef>(null)
	const SWITCH = useGlobalStore((state) => state.SWITCH)

	return (
		<Modal
			width={430}
			height={300}
			open={isOpen}
			title={dialogTitle}
			onCancel={() => {
				update({ isOpen: false })
			}}
			okText={t('保存')}
			onOk={async () => {
				let valid = await inputRef.current?.valid()
				if (!valid) return
				handleConfirm()
			}}
			cancelText={t('取消')}
		>
			<Wrap>
				<div className="pre_title">{t('预案列表')}</div>
				<div className="content">
					{planOptions.length > 0 ? (
						planOptions.map((item) => {
							return (
								<div
									onClick={() => {
										handlePlanClick(item)
									}}
									className="plan-item"
									key={item.value}
								>
									{item.label}
								</div>
							)
						})
					) : (
						<div className="list-empty">
							<IconTips></IconTips>
							<div className="emptymsg" title={emptyMsg}>
								{emptyMsg}
							</div>
						</div>
					)}
				</div>
				<div className="plan">
					<div className="plan-label">{t('预案名称')}</div>
					<Input
						width={340}
						value={name}
						placeholder={t('请输入预案名称')}
						focusMsg={
							SWITCH.characterLimit
								? t('可输入16个字符，包括汉字、英文大小写字母、数字、. 、空格')
								: undefined
						}
						innerRef={inputRef}
						maxLength={16}
						rule={{
							required: {
								showIcon: false,
								msg: t('预案名称不能为空'),
							},
							regular: getCheckPreNameRule(SWITCH.characterLimit),
						}}
						onChange={(e, v) => {
							update({ name: v })
						}}
					/>
				</div>
			</Wrap>
		</Modal>
	)
}
export default Main
